package jdec.jdt.ls.decompiler.common.util;

import java.util.Map;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;

public class EclipseFormater {
    public String formatSource(String source) {
        String result = null;

        if (source == null) {
            return null;
        }

        CompilerOptions option = new CompilerOptions();
        Map<String, String> options = option.getMap();
        options.put(CompilerOptions.OPTION_Compliance, DecompilerOutputUtil.getMaxDecompileLevel()); // $NON-NLS-1$
        options.put(CompilerOptions.OPTION_Source, DecompilerOutputUtil.getMaxDecompileLevel()); // $NON-NLS-1$
        CodeFormatter formatter = ToolFactory.createCodeFormatter(options);
        TextEdit textEdit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, source, 0, source.length(), 0, null);
        if (textEdit != null) {
            IDocument document = new Document(source);
            try {
                textEdit.apply(document);
                result = document.get();
            } catch (MalformedTreeException | org.eclipse.jface.text.BadLocationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        if (result == null) {
            // JavaDecompilerPlugin.log(IStatus.WARNING, null, "Could not format code, it will
            // remain unformatted."); //$NON-NLS-1$
            result = source;
        }

        return result.strip();
    }
}
